﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CTEM.Controllers.BUS;
using CTEM.Controllers.Global;
using CTEM.Models;
using DevExpress.XtraBars;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;

namespace CTEM.ModuleForms.ManageVehicle
{
    public partial class VehicleManagement : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        private readonly VehicleBUS _vehicleBus = new VehicleBUS();
        private readonly ConstructionBUS _constructionBus = new ConstructionBUS();
        private readonly EmployeeBUS _employeeBus = new EmployeeBUS();
        private readonly WarehouseBUS _warehouseBus = new WarehouseBUS();
        private List<VH_VehicleDTO> _listVehicle = new List<VH_VehicleDTO>();
        private readonly List<VH_VehicleDTO> _listVehicleHistory = new List<VH_VehicleDTO>();

        private  List<CS_ConstructionDTO> _listConstruction = new List<CS_ConstructionDTO>();
        private  List<WH_WarehouseDTO> _listWarehouse = new List<WH_WarehouseDTO>();
        private bool _isNew;
        private bool _isUpdate;

        public VehicleManagement()
        {
            InitializeComponent();
            LoadVehicle();
            repositoryItemComboBox2.Items.AddRange(VH_VehicleDTO.getCategory());
            //_listConstruction.Insert(0, new ConstructionDTO("", 0));
            _isNew = false;
            _isUpdate = false;
        }
        public void LoadColumn()
        {
            gridView1.Columns["ConstructionID"].OptionsColumn.AllowEdit = false;
            gridView1.Columns["WarehouseID"].OptionsColumn.AllowEdit = false;
        }
        public void LoadVehicle()
        {
            _listVehicle = _vehicleBus.LoadAllVehicles();
            //_listWarehouse = _warehouseBus.LoadWarehouses("", Constants.MAIN_WAREHOUSE, -1);
            //_listConstruction = _constructionBus.LoadAllConstructions();

            vehicleDTOBindingSource.DataSource = _listVehicle;
            constructionDTOBindingSource.DataSource = _listConstruction;
            warehouseDTOBindingSource.DataSource = _listWarehouse;
            employerDTOBindingSource.DataSource = _employeeBus.LoadAllUser();
            LoadColumn();
        }

        private static VH_VehicleDTO ConvertVehicle (VH_VehicleDTO vehicle)
        {
            if(!String.IsNullOrEmpty(vehicle.Name))
            vehicle.Name = Global.TitleCase(vehicle.Name.TrimEnd());
            if (!String.IsNullOrEmpty(vehicle.Number))
            vehicle.Number = Global.RemoveSpace(vehicle.Number);

            return vehicle;
        }

        private void CheckWarehouseAndConstruction(VH_VehicleDTO vehicle)
        {
            if (vehicle.WarehouseID == 0 && vehicle.ConstructionID == 0)
            {
                gridView1.Columns["ConstructionID"].OptionsColumn.AllowEdit = true;
                gridView1.Columns["WarehouseID"].OptionsColumn.AllowEdit = true;
                return;
            }
            if (vehicle.WarehouseID == 0 && vehicle.ConstructionID != 0)
            {
                gridView1.Columns["ConstructionID"].OptionsColumn.AllowEdit = true;
                gridView1.Columns["WarehouseID"].OptionsColumn.AllowEdit = false;
                return;
            }
            if (vehicle.ConstructionID == 0 && vehicle.WarehouseID != 0)
            {
                gridView1.Columns["WarehouseID"].OptionsColumn.AllowEdit = true;
                gridView1.Columns["ConstructionID"].OptionsColumn.AllowEdit = false;
                return;
            }
        }

        private bool ValidateVehicle(VH_VehicleDTO vehicle, out string output, out int i)
        {
            i = 0;
            if (String.IsNullOrEmpty(vehicle.Name))
            {
                output = "Xin hãy nhập Tên phương tiện";
                i = 0;
                return false;
            }
             if (String.IsNullOrEmpty(vehicle.Number))
            {
                i = 1;
                output = "Xin hãy nhập Biển Số";
                return false;
            }
            foreach (var vehicleDto in _listVehicle)
            {
                if (!vehicleDto.Number.ToUpper().Trim().Equals(vehicle.Number.ToUpper().Trim()) ||
                    vehicleDto.VehicleID.CompareTo(vehicle.VehicleID) == 0) continue;
                i = 1;
                output =
                    string.Format("Biển số \"{0}\" mà bạn vừa nhập đã tồn tại.\n Vui lòng nhập lại số khác.", vehicle.Number);
                return false;
            }
             if (String.IsNullOrEmpty(vehicle.Status))
            {
                i = 5;
                output = "Xin hãy nhập Tình Trạng";
                return false;
            }
             if (String.IsNullOrEmpty(vehicle.Category))
            {
                i = 6;
                output = "Xin hãy chọn Loại";
                return false;
            }
            output = "";
            return true;
        }

       private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            _isNew = true;
            gridView1.SetRowCellValue(e.RowHandle,"Date",DateTime.Today);
        }

        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (_isNew)
            {
                var view = sender as ColumnView;
                var vehicle = e.Row as VH_VehicleDTO;
                var chk = true;

                vehicle = ConvertVehicle(vehicle);
                CheckWarehouseAndConstruction(vehicle);

                if (chk)
                {
                    String message = null;
                    int pos = -1;
                    if (!ValidateVehicle(vehicle, out message, out pos))
                    {
                        e.Valid = false;
                        if (view != null)
                        {
                            view.ClearColumnErrors();
                            view.SetColumnError(view.Columns[pos], message, ErrorType.Warning);
                        }
                        DialogResult result = MessageBox.Show(message + "\nBạn có muốn nhập lại thông tin", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (result == DialogResult.No)
                        {
                            _isNew = false;
                            e.Valid = true;
                            LoadVehicle();
                        }
                    }
                    else
                    {
                        long success = _vehicleBus.CreateVehicle(vehicle);
                        if (success == 0)
                        {
                            e.Valid = false;
                        }
                        else
                        {
                            if (vehicle != null)
                            {
                                vehicle.VehicleID = success;
                                vehicle._Status = 1;
                                _listVehicleHistory.Add(vehicle);
                            }
                            _isNew = false;
                            LoadVehicle();
                        }
                    }
                }

            }
        }

        private void gridView1_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (!_isNew)
            {
                var view = sender as ColumnView;
                var i = e.RowHandle;
                var vehicle = gridView1.GetRow(i) as VH_VehicleDTO;
                if (vehicle != null)
                {
                    var oldVehicle = _vehicleBus.GetVehicleByID(vehicle.VehicleID);
                    var message = "";
                    var pos = -1;

                    vehicle = ConvertVehicle(vehicle);
                    CheckWarehouseAndConstruction(vehicle);

                    if (!ValidateVehicle(vehicle, out message, out pos))
                    {
                        DialogResult result = MessageBox.Show(message + "\nBạn có muốn nhập lại thông tin", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (view != null)
                        {
                            view.SetColumnError(view.Columns[pos], message, ErrorType.Warning);
                            if (result == DialogResult.No)
                            {
                                _isUpdate = false;
                                view.ClearColumnErrors();
                                LoadVehicle();
                                return;
                            }
                            else
                            {
                                _isUpdate = true;
                                gridView1.FocusedRowHandle = i;
                                gridView1.FocusedColumn = e.Column;
                                return;
                            }
                        }
                    }
                    if (!_vehicleBus.UpdateVehicle(vehicle))
                    {
                        MessageBox.Show("Không thể cập nhật thông tin nhân viên", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        _isUpdate = false;
                    }
                    else
                    {
                        _isUpdate = false;
                        if (oldVehicle != null)
                        {
                            oldVehicle._Status = 2;
                            _listVehicleHistory.Add(oldVehicle);
                        }
                    }
                }
            }
        }

        private void gridView1_InvalidRowException(object sender, InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = ExceptionMode.NoAction;
        }

        private void gridView1_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            if (e.PrevFocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle)
            {
                if (_isNew)
                {
                    gridView1.FocusedRowHandle = GridControl.NewItemRowHandle;
                }
            }
            if (_isUpdate)
            {
                _isUpdate = false;
                LoadVehicle();
            }
        }

        private void btnDelete_ItemClick(object sender, ItemClickEventArgs e)
        {
            int rowIndex = gridView1.FocusedRowHandle;
            var vehicle = gridView1.GetRow(rowIndex) as VH_VehicleDTO;
            if (vehicle != null)
                if (MessageBox.Show(string.Format("Bạn có chắc chắn muốn xóa phương tiện \"{0}\" không?", vehicle.Name), "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    bool success = _vehicleBus.delete(vehicle.VehicleID);
                    if (success)
                    {
                        LoadVehicle();
                        vehicle._Status = 3;
                        _listVehicleHistory.Add(vehicle);
                    }
                    else
                        MessageBox.Show("Không thể xóa phương tiện này.", "Cảnh báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
        }

        private void btnUndo_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (_listVehicleHistory.Count <= 0) return;
            var undoItem = _listVehicleHistory[_listVehicleHistory.Count - 1];
            switch (undoItem._Status)
            {
                case 1:
                    foreach (var vehicle in _listVehicle)
                        if (undoItem.VehicleID == vehicle.VehicleID)
                        {
                            _vehicleBus.delete(vehicle.VehicleID);
                            _listVehicleHistory.RemoveAt(_listVehicleHistory.Count - 1);           
                            LoadVehicle();
                            break;
                        }
                    break;
                case 2:
                    foreach (var vehicle in _listVehicle)
                        if (undoItem.VehicleID == vehicle.VehicleID)
                        {
                            _vehicleBus.UpdateVehicle(undoItem);
                            _listVehicleHistory.RemoveAt(_listVehicleHistory.Count - 1);
                            LoadVehicle();
                            break;
                        }
                    break;
                case 3:
                    _vehicleBus.CreateVehicle(undoItem);
                    _listVehicleHistory.RemoveAt(_listVehicleHistory.Count - 1);
                    LoadVehicle();
                    break;
                default:
                    break;
            }
        }

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            var vehicle = gridView1.GetRow(e.RowHandle) as VH_VehicleDTO;
            if (vehicle != null)
            {
                CheckWarehouseAndConstruction(vehicle);
            }
        }
      }
}